package com.agent.course.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.agent.commons.errorcode.ControllerErrorCodeConstants;
import com.agent.commons.errorcode.ServiceErrorCodeConstants;
import com.agent.commons.exception.BaseException;
import com.agent.course.dataobject.ClassBaseDO;
import com.agent.course.mapper.ClassMapper;
import com.agent.course.mapper.ClassMemberMapper;
import com.agent.course.param.ClassParam;
import com.agent.course.service.ClassService;
import com.agent.course.vo.TeacherClassVO;
import jakarta.annotation.Priority;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ClassServiceImpl implements ClassService {
    @Resource
    private ClassMapper classMapper;

    @Autowired
    private ClassMemberMapper classMemberMapper;


    /**
     * 新建课程(教师端)
     * @param classParam
     * @return
     */
    @Override
    public ClassBaseDO addClass(ClassParam classParam) {
        if(classParam.getUserId()==null||classParam.getClassName()==null){
            throw new BaseException(ServiceErrorCodeConstants.PARAM_ERROR);
        }
        String classId = makeClassId();
        classParam.setClassId(classId);
        if(classMapper.addClass(classParam)==0){
            throw new BaseException(ControllerErrorCodeConstants.INSERT_ERROR);
        }
        ClassBaseDO classBaseDO=new ClassBaseDO();
        classBaseDO.setClassId(classId);
        classBaseDO.setClassName(classParam.getClassName());
        return classBaseDO;
    }


    /**
     * 查询教师所建所有课程(教师端)
     * @param userId
     * @return
     */
    @Override
    public List<TeacherClassVO> getTeacherClasses(String userId) {
        return classMapper.getTeacherClasses(userId);
    }

    /**
     * 获取学生参加的课程(学生端)
     * @param userId
     * @return
     */
    @Override
    public List<TeacherClassVO> getStudentClasses(String userId) {
        List<String> studentClassesId = classMemberMapper.getStudentClassesId(userId);
        return studentClassesId.stream().map(classId ->
                classMapper.getStudentClasses(classId)).toList();
    }

    /**
     * 随机生成课程id
     * @return
     */
    private String makeClassId(){
        String classId = RandomUtil.randomNumbers(8);
        while(classMapper.countByClassId(classId)!=0){
            classId=RandomUtil.randomNumbers(8);
        }
        return classId;
    }
}
